import AModal from '@/components/AModal';
import { selectSellPage } from '@/services/goods/productManage';
import { BetaSchemaForm, ProCard } from '@ant-design/pro-components';
import { useDispatch, useSelector } from '@umijs/max';
import { useRequest, useSetState } from 'ahooks';
import { Table } from 'antd';
import { useEffect } from 'react';
import { columns } from './columns';

export default () => {
  const {
    integralGoods: { visible },
  } = useSelector((state) => state);
  const dispatch = useDispatch();
  const update = (data) => {
    dispatch({
      type: 'integralGoods/update',
      payload: data,
    });
  };
  const [state, setState] = useSetState({
    searchForm: {},
    dataSource: [],
    pageNum: 1,
    pageSize: 10,
    total: 0,
  });

  const { dataSource, searchForm, pageNum, pageSize, total } = state;

  const { run, loading } = useRequest(selectSellPage, {
    manual: true,
    onSuccess: async ({ code, data, total }) => {
      if (code && code === 200) {
        setState({
          dataSource: data || [],
          total: total,
        });
      }
    },
  });

  useEffect(() => {
    if (visible) {
      run({
        pageNum,
        pageSize,
        hasPointsRule: true,
        ...searchForm,
      });
    }
  }, [pageNum, pageSize, searchForm, visible]);

  const handleEdit = (type, record) => {
    if (type === 'edit') {
      close();
      update({
        editData: {
          ...record,
          itemId: record.id,
        },
        editVisible: true,
      });
    }
  };

  const close = () => {
    setState({
      searchForm: {},
      dataSource: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
    });
    update({ visible: false });
  };

  const orderTableProps = {
    pagination: {
      current: pageNum,
      pageSize,
      total,
      onChange: (page, pageSize) => {
        setState({ pageNum: page, pageSize: pageSize });
      },
      showTotal: (total) => `第 ${pageNum}-${dataSource.length} 条/总共 ${total} 条`,
    },
    bordered: true,
    dataSource,
    columns: columns({ handleEdit }),
    loading: loading,
    rowKey: 'id',
  };

  return (
    <AModal open={visible} width={1000} onCancel={close} footer={null}>
      <ProCard title="选择商品" headerBordered bodyStyle={{ paddingBottom: 0 }}>
        <BetaSchemaForm
          labelAlign="right"
          labelWidth={70}
          layoutType="QueryFilter"
          onFinish={(values) => {
            setState({ searchForm: values, pageNum: 1 });
          }}
          onReset={() => {
            setState({ searchForm: {}, pageNum: 1 });
          }}
          columns={[
            {
              title: '商品ID',
              dataIndex: 'id',
            },
          ]}
        />
        <Table {...orderTableProps} />
      </ProCard>
    </AModal>
  );
};
